package top.chenfu.cloud.order.controller;

import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.chenfu.cloud.commons.Item;
import top.chenfu.cloud.commons.Order;
import top.chenfu.cloud.commons.util.ResponseData;
import top.chenfu.cloud.order.fetch.ItemFetch;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @Auther chenfu
 * @2019/12/5 20:12
 * @Desc
 */
@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private ItemFetch itemFetch;

    private static HashMap<String, Order> orders = Maps.newHashMap();

    @PostMapping(value = "add", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseData<Order> addOrder(@RequestParam(value = "itemIds") String itemIds) {
        List<String> ids = Arrays.asList(itemIds.split(","));
        if (CollectionUtils.isEmpty(ids)) {
            ResponseData.defaultFail();
        }
        List<String> iIds = ids.stream().map(id -> {
            ResponseData<Item> itemById = itemFetch.getItemById(id);
            return itemById.getData().getId();
        }).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(iIds)) {
            return ResponseData.defaultFail();
        }
        Order order = new Order();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        order.setId(uuid);
        order.setItemIds(iIds);
        orders.put(uuid, order);
        return ResponseData.defaultSuccess(order);
    }

    @GetMapping(value = "get/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseData getOrder(@Validated @PathVariable String id, BindingResult result) {
        if (result.hasErrors() || StringUtils.isEmpty(id)) {
            ResponseData.defaultFail();
        }
        Order order = orders.get(id);
        return ResponseData.defaultSuccess(order);
    }

    @GetMapping(value = "all", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseData getAll() {
        return ResponseData.defaultSuccess(orders);
    }

}
